package com.yrihr.wisdom.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yrihr.wisdom.common.ResponseBody;
import com.yrihr.wisdom.common.ResponseCode;
import com.yrihr.wisdom.dto.RiverDto;
import com.yrihr.wisdom.entity.Interval;
import com.yrihr.wisdom.entity.River;
import com.yrihr.wisdom.service.IntervalService;
import com.yrihr.wisdom.service.RiverService;
import com.yrihr.wisdom.vo.RiverVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName : RiverController
 * @Description : river
 * @Author : wind
 * @Date: 2020-12-17 15:02
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/api/river")
@RequiredArgsConstructor
public class RiverController {

    private final RiverService riverService;
    private final IntervalService intervalService;

    @RequestMapping("/insertBatch")
    public String insertRiver() {
        List<River> rivers = new ArrayList<>();
        SnowflakeShardingKeyGenerator id = new SnowflakeShardingKeyGenerator();

        for (int i = 1; i < 42; i++) {
            rivers.add(new River((Long) id.generateKey(),
                    new Random().nextInt(1) + 13,
                    "河道" + i,
                    "站名" + i,
                    6L,
                    new Date(),
                    Double.valueOf(String.format("%.2f", new Random().nextDouble() * 100 + 1)),
                    "",
                    Double.valueOf(String.format("%.2f", new Random().nextDouble() * 100 + 100))));
        }

        boolean b = riverService.saveBatch(rivers);
        if (b) {
            return "插入成功！";
        } else {
            return "插入失败！";
        }
    }

    /**
     * 查询站点信息
     *
     * @return
     */
    @RequestMapping("/selectInterval")
    public ResponseBody selectInterval() {
        List<Interval> intervalList = intervalService.selectInterval();
        if (intervalList != null && intervalList.size() > 0) {
            return ResponseBody.success(ResponseCode.SUCCESS, intervalList);
        } else {
            return ResponseBody.success(ResponseCode.ERROR, null);
        }
    }

    /**
     * 分页查询
     *
     * @param page
     * @return
     * @throws Exception
     */
    @RequestMapping("/page")
    public ResponseBody selectPageRiver(@RequestBody RiverDto page) throws Exception {
        if (page != null) {
            long current = page.getCurrent();
            long size = page.getSize();
            RiverVo riverVo = new RiverVo();
            if (page.getInterval() != null && page.getInterval().size() > 0) {
                riverVo.setIntervalList(page.getInterval());
            }
            if (page.getStartTime() != null && page.getStartTime() + "" != "") {
                riverVo.setStartTime(page.getStartTime());
            }
            if (page.getEndTime() != null && page.getEndTime() + "" != "") {
                riverVo.setEndTime(page.getEndTime());
            }
            IPage<River> up = riverService.selectPage(current, size, riverVo);
            if (up != null) {
                return ResponseBody.success(ResponseCode.SUCCESS, up);
            } else {
                return ResponseBody.error(ResponseCode.ERROR, null);
            }
        } else {
            return ResponseBody.error(ResponseCode.ERROR, null);
        }
    }

    @PostMapping("/download")
    public void download(HttpServletResponse response, @RequestBody RiverDto river) throws IOException {
        RiverVo riverVo = new RiverVo();
        if (river != null) {
            if (river.getStartTime() != null && river.getStartTime() + "" != "") {
                riverVo.setStartTime(river.getStartTime());
            }
            if (river.getEndTime() != null && river.getEndTime() + "" != "") {
                riverVo.setEndTime(river.getEndTime());
            }
            if (river.getInterval() != null && river.getInterval().size() > 0) {
                riverVo.setIntervalList(river.getInterval());
            }
        }
        List<River> list = riverService.selectRiverDownload(riverVo);
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String datePath = simpleDateFormat.format(new Date());
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(datePath + "-" +
                UUID.randomUUID().toString().replaceAll("-",""),"UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), River.class).sheet("river").doWrite(list);
    }
}
